package com.scpii.universal.util;

import java.text.DecimalFormat;

public class CoordinateUtil {
	static double M_PI = Math.PI;
	DecimalFormat df = new DecimalFormat("0.0"); 
	
	public static String formatNum(double value) {
		String retValue = null;
		DecimalFormat df = new DecimalFormat();
		df.setMinimumFractionDigits(0);
		df.setMaximumFractionDigits(0);
		retValue = df.format(value);
		retValue = retValue.replaceAll(",", "");
		return retValue;
	}
	
	public static String formatDistance(double value) {
		double result = Double.valueOf(formatNum(value));
		if(result < 1000)
			return result+"米";
		else
			return formatNum(result/1000) + "公里";
	}

	// 经纬度转摩卡托
	// 经度(lon)，纬度(lat)
	public static double[] lonLat2Mercator(double lon, double lat) {
		double[] xy = new double[2];
		double x = lon * 20037508.342789 / 180;
		double y = Math.log(Math.tan((90 + lat) * M_PI / 360)) / (M_PI / 180);
		y = y * 20037508.34789 / 180;
		xy[0] = x;
		xy[1] = y;
		return xy;
	}

	// 摩卡托转经纬度
	public static double[] Mercator2lonLat(double mercatorX, double mercatorY) {
		double[] xy = new double[2];
		double x = mercatorX / 20037508.34 * 180;
		double y = mercatorY / 20037508.34 * 180;
		y = 180 / M_PI * (2 * Math.atan(Math.exp(y * M_PI / 180)) - M_PI / 2);
		xy[0] = x;
		xy[1] = y;
		return xy;
	}
	
	public static double calc2PointDistance(double[] pointA,double[] pointB) {
		return Math.sqrt(Math.pow((pointB[0] - pointA[0]),2) + Math.pow((pointB[1] - pointA[1]),2));
	}

	public static void main(String[] args) {
		double[] num;
		num = lonLat2Mercator(108.312241,  22.787823);
		for (int i = 0; i < num.length; i++) {
			System.out.println(formatNum(num[i]));
		}
		double[] pointA = {104.384375038975,31.1040172360304};
		double[] pointB = {104.05273359,30.543241019999993};
		System.out.println(calc2PointDistance(pointA, pointB));
		
		double[] pointC = {12057263.51,2606379.51};
		double[] pointD = {12058495.49,2609268.08};
		System.out.println(calc2PointDistance(pointC, pointD));
	}

}
